package com.game.spacetrader.TradeGoods;

import java.util.ArrayList;

import com.game.spacetrader.Game;
import com.game.spacetrader.R;
import com.game.spacetrader.data.SaveGame;
import com.game.spacetrader.map.MapView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

/**
 * Class for the Market tab
 */
public class TradeGoodsMarket extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tradegoodslist);
		setUp();
	}
	
	/**
	 * Handles ListView and ListView events
	 */
	public void setUp() {
		ListView marketList = (ListView) findViewById(R.id.tradeList);
		TextView playerPoints = (TextView) findViewById(R.id.playerPointsTV);
		playerPoints.setText("Points: " +  Game.getInstance().getPlayer().getPoints()+"\nCargo: "+Game.getInstance().getPlayer().getCargoSize()+"/"
				+Game.getInstance().getPlayer().getMaxCargo()+"\nGas: "+Game.getInstance().getPlayer().getGas()+"\nPlanet: " + Game.getInstance().getCurrentPlanet().getName()+"\nCondition: "
				+" "+Game.getInstance().getCurrentPlanet().getEvent().getEvent());
		
		final ArrayList<TradeGoods> market = TradeGoodsAdaptor.goods;
		final ArrayList<String> listString = new ArrayList<String>();
		for(TradeGoods i: market)
			listString.add(i.toString() + "\n - Price: " + i.price() + "\n - Quantity: " + i.getQuantityHave());
		
        ArrayAdapter<String> arrayAdapter =      
        new ArrayAdapter<String>(this,R.layout.tradegoodslistcolor, listString);
        marketList.setAdapter(arrayAdapter); 
        
		marketList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			/**
			 * Called when item on list is selected
			 */
			public void onItemClick(AdapterView<?> arg0, final View v, int index,
					long id) {
				
				final TextView view = (TextView) v; 
				if(!(Game.getInstance().getPlayer().getCargoSize() + market.get(listString.indexOf(view.getText())).getQuantity() > Game.getInstance().getPlayer().getMaxCargo()))
				if(!(((market.get(listString.indexOf(view.getText())).getPrice()) > Game.getInstance().getPlayer().getPoints()))) {
			    	
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(arg0.getContext());
					
					LayoutInflater inflater = getLayoutInflater();
				
				    final View alertView = inflater.inflate(R.layout.tradegoodsalert, null);
				    ((TextView) alertView.findViewById(R.id.textView2)).setText("0 units of " + market.get(listString.indexOf(view.getText())) + " Selected");
				    final SeekBar bar = (SeekBar) alertView.findViewById(R.id.seekBar1);
				    
				    //Sets size of bar to quantity available or space available in hull
				    int max = market.get(listString.indexOf(view.getText())).getQuantityHave();
				    if(Game.getInstance().getPlayer().getMaxCargo() - Game.getInstance().getPlayer().getCargoSize() < max)
				    	max = Game.getInstance().getPlayer().getMaxCargo() - Game.getInstance().getPlayer().getCargoSize();
				    if(Game.getInstance().getPlayer().getPoints()/market.get(listString.indexOf(view.getText())).getPrice()<max)
				    	max = Game.getInstance().getPlayer().getPoints()/market.get(listString.indexOf(view.getText())).getPrice();
				    /*Sets size of bar*/
				    bar.setMax(max);
				    bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
				    
				    	/**
				    	 * Adjusts number of items shown when seekbar moved
				    	 */
						public void onProgressChanged(SeekBar seekBar,
								int progress, boolean fromUser) {
							((TextView) alertView.findViewById(R.id.textView2)).setText("" + progress + " units of " + market.get(listString.indexOf(view.getText())) + " Selected");
						}

						public void onStartTrackingTouch(SeekBar seekBar) {
							// TODO Auto-generated method stub
							
						}

						public void onStopTrackingTouch(SeekBar seekBar) {
							// TODO Auto-generated method stub
							
						}
				    	
				    });
				    
					alertDialogBuilder.setTitle("Market");					
					alertDialogBuilder
						.setMessage("How many units of " + market.get(listString.indexOf(view.getText())) + " do you want to buy?")
						.setCancelable(false)
						.setPositiveButton("Confirm",new DialogInterface.OnClickListener() {
							/**
							 * Buys item, removes points, removes from market, adds to hull, refreshes screen
							 */
							public void onClick(DialogInterface dialog,int id) {
								if(market.get(listString.indexOf(view.getText())).getName().equals("gas")){
									Game.getInstance().getPlayer().setPoints(Game.getInstance().getPlayer().getPoints() - (market.get(listString.indexOf(view.getText())).getPrice() * bar.getProgress()));									
									market.get(listString.indexOf(view.getText())).setQuantityHave(market.get(listString.indexOf(view.getText())).getQuantityHave() - bar.getProgress());
									Game.getInstance().getPlayer().setGas(Game.getInstance().getPlayer().getGas()+bar.getProgress());
									setUp();
								}
								else{
									Game.getInstance().getPlayer().setPoints(Game.getInstance().getPlayer().getPoints() - (market.get(listString.indexOf(view.getText())).getPrice() * bar.getProgress()));									
									market.get(listString.indexOf(view.getText())).setQuantityHave(market.get(listString.indexOf(view.getText())).getQuantityHave() - bar.getProgress());
									Game.getInstance().getPlayer().getCargo().get(listString.indexOf(view.getText())).setQuantityHave(Game.getInstance().getPlayer().getCargo().get(listString.indexOf(view.getText())).getQuantityHave() + bar.getProgress());
									Game.getInstance().getPlayer().addCargoSize(bar.getProgress());
									setUp();
								}
								}
							  })
							.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
								/**
								 * Closes window
								 */
								public void onClick(DialogInterface dialog,int id) {
									dialog.cancel();
								}
							});
							final AlertDialog alertDialog = alertDialogBuilder.create();
							alertDialog.setView(alertView);
							alertDialog.show();
				}
				else { 
					failDialog("you cannot afford that item");
				}
				else {
					failDialog("Not enough room for that item."); 
				}
			}
		});
	}
	
	/**
	 * Called to start AlertDialog. String passed in is message for dialog
	 * 
	 * @param string
	 */
	public void failDialog(String string) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(TradeGoodsMarket.this);
		alertDialogBuilder.setTitle("Error");
			
		alertDialogBuilder
			.setMessage(string)
			.setCancelable(false)
			.setPositiveButton("Okay",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					dialog.cancel();
				}
		  });
	      AlertDialog alertDialog = alertDialogBuilder.create();
		  alertDialog.show();
	}
	
	/**
	 * Creates option menu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_space_trader, menu);
	    return true;
	}
	
	/**
     * Listener for the options menu
     * @param item the item in the Menu that is clicked
     */
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.travel:
	        	Intent i = new Intent(this, MapView.class);
	        	startActivity(i);
	            return true;
	        case R.id.market:
	        	Intent i2 = new Intent(this, TradeGoodsView.class); startActivity(i2);
	        	return true;
	        case R.id.save:
	        	SaveGame saveGame = new SaveGame();
	        	saveGame.save((Context) this);
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
}